<?php
/**
 * 创瑞网短信发送接口
 * User: yu
 * Date: 16-11-14
 * Time: 下午3:40
 */
namespace utils\sms;

use herosphp\core\Log;

class Cr6868Provider
{
    private $user = null;
    private $pass = null;
    private $key = null;
    private $sign = null;
    private $authed = false;

    public function auth($user, $pass, $key, $sign)
    {
        $this->user = $user;
        $this->pass = $pass;
        $this->key = $key;
        $this->sign = $sign;
        $this->authed=true;
    }

    /**
     * @param $mobile 请用自己的手机号代替
     * @param $content //
     * @param string $sendTime
     * @return boolean 成功返回ture,失败返回fasle
     */

    public function send($mobile, $content, $sendTime){
        if(!$mobile || !$content) return false;
        return $this->sendSms($this->user, $this->pass, $mobile, $content, $sendTime);
    }

    private function sendSms($user, $password, $mobiles, $message, $sendTime){
        $gateway = 'http://web.cr6868.com/asmx/smsservice.aspx';
        $datas = array(
            //'SpCode' =>self::$SpCode,
            'name' => $user, // 用户账号
            'pwd' => $password, // MD5位32密码
            'mobile' => $mobiles, // 号码
            'content' => $message, // 内容
            'type' => 'pt',
            'sign'=>$this->sign,
            'stime'=>''
        );
        $result = $this->postSms($gateway, $datas); // POST方式提交

        if(substr($result, 0, 1) == '0') {

            Log::info("发送短信返回结果:成功->" . json_encode($result));
            return true;
        }else{

            Log::info("发送短信返回结果:失败->" . json_encode($result));
            return false;
        }
    }

    private function postSms($gateway, $datas){
        $dateway = parse_url($gateway);
        $host = $dateway['host'];
        $port = $dateway['port']? $dateway['port'] : 80;
        $file = $dateway['path'];
        while(list($k, $v) = each($datas)){
            $posts .= rawurlencode($k) . "=" . rawurlencode($v) . "&"; // 转URL标准码
        }
        $posts = substr($posts, 0, -1);
        $len = strlen($posts);
        $fp = @fsockopen($host, $port, $errno, $errstr, 10);
        if(!$fp){
            return "$errstr ($errno)\n";
        }else{
            $receive = '';
            $out = "POST $file HTTP/1.1\r\n";
            $out .= "Host: $host\r\n";
            $out .= "Content-type: application/x-www-form-urlencoded\r\n";
            $out .= "Connection: Close\r\n";
            $out .= "Content-Length: $len\r\n\r\n";
            $out .= $posts;
            fwrite($fp, $out);
            while(!feof($fp)){
                $receive .= fgets($fp, 128);
            }
            fclose($fp);
            $receive = explode("\r\n\r\n", $receive);
            unset($receive[0]);
            return implode("", $receive);
        }
    }
}

?>